package ctrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import service.IBookService;
import service.ICartLineService;
import service.Impl.IBookServiceImpl;
import service.Impl.ICartLineServiceImpl;
import service.Impl.ICartServiceImpl;
import vo.Book;
import vo.Cart;
import vo.CartLine;
import vo.Client;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/*
* @description: 接收page属性(每页三个数据)，返回三个数据
*/
public class showCart extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        HttpSession httpSession=req.getSession();
        Client client= (Client) httpSession.getAttribute("client");
        if(client!=null){
            int userId=client.getId();

            ICartServiceImpl cartService=new ICartServiceImpl();
            Cart cart= cartService.selectCart(userId);
            double totalPrice = cart.getTotalPrice();
            ICartLineServiceImpl cartLineService=new ICartLineServiceImpl();
            List<CartLine>cartLines=cartLineService.selectCartLineByCartId(cart.getId());

            IBookServiceImpl bookService=new IBookServiceImpl();


            //将cartline对象封装成json对象
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("cart",cart);

            JSONArray jsonArray=new JSONArray();
            for(CartLine cartLine1:cartLines){
                Book book=bookService.selectBookById(cartLine1.getBookId());
                JSONObject jo=new JSONObject();
                jo.put("id",cartLine1.getId());
                jo.put("bookId",cartLine1.getBookId());
                jo.put("name",book.getName());
                jo.put("breifIntro",book.getBriefIntro());
                jo.put("price",book.getPrice());
                jo.put("type",book.getType());
                jo.put("imgUrl",book.getImgUrl());
                jo.put("quanlity",cartLine1.getQuanlity());
                jsonArray.add(jo);
            }

            jsonObject1.put("cartLines",jsonArray);
            int size = jsonArray.size();
            httpSession.setAttribute("cartSize",size);
            httpSession.setAttribute("totalPrice",totalPrice);
            resp.getWriter().write(jsonObject1.toString());
        }else{
            resp.getWriter().write("{\"status\":102}");
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


}
